﻿using ZenSystemService.Api.Data;
using ZenSystemService.Api.Entities;

namespace ZenSystemService.Api.Services
{
    public class SMSVerificationCodeService
    {
        private readonly ApplicationDbContext _context;

        public SMSVerificationCodeService(ApplicationDbContext context)
        {
            _context = context;
        }

        /// <summary>
        /// 添加验证码信息
        /// </summary>
        /// <param name="_smsVerificationCodeService"></param>
        /// <returns></returns>
        public async Task<bool> AddSMSVerificationCodeAsync(SMSVerificationCode _smsVerificationCode)
        {
            try
            {
                _context.SMSVerificationCodes.Add(_smsVerificationCode);
                int count = await _context.SaveChangesAsync();
                return count > 0 ? true : false;
            }
            catch (Exception ex)
            {
                return false;
            }
        }



        /// <summary>
        /// 验证手机验证码
        /// </summary>
        /// <param name="phone"></param>
        /// <param name="code"></param>
        /// <returns></returns>
        public async Task<bool> ValidateVerificationCode(string phone, string code)
        {
            var firstItem = _context.SMSVerificationCodes.Where(item => item.Phone == phone).OrderByDescending(item => item.SendTime);
            if (firstItem == null || firstItem.Count<SMSVerificationCode>() == 0)
                return false;
            List<SMSVerificationCode> list = firstItem.ToList<SMSVerificationCode>();
            if (code == list[0].VerificationCode)
            {
                TimeSpan difference = System.DateTime.Now - list[0].SendTime; // 计算时间差
                double secondsDifference = difference.TotalSeconds; // 转换为总秒数
                if (secondsDifference <= 60)
                    return true;
                else
                    return false;
            }
            else
            {
                return false;
            }
        }

    }
}
